#!/usr/bin/env bash
# Dropbox + Bash = Lighting Fast .gif retrieval
# -----------------------
# Usage: gif <part-of-gif-basename>
# Prerequisites: 
#     - keep a butt-load of gifs in your "$HOME/Dropbox/Public/gifs" folder
#     - Export a DROPBOX_UID variable that has your dropboxusercontent id
#     - ...like a boss (https://dl.dropboxusercontent.com/u/2372716/gifs/like-a-boss.gif)
arg=$1

if [ -z $1 ]; then
    arg='.'
fi

db_path=http://tyler.zone/public/gifs/

j=0
while read file; do
  files[ $j ]="$file"
  (( j++ ))
done < <(ls "$HOME/Sync/Public/gifs" | grep -i "$arg")

# Less options:
#   -F or --quit-if-one-screen
#   -i or --ignore-case (this is smart ignore case)
#   -r or --raw-control-chars
#   -S or --chop-long-lines (no line wrap)
#   -X or --no-init (doesn't clear screen on escape)
printf "%s\n" "${files[@]}" | nl | less -FirSX
printf "[ $(tput setaf 2)?$(tput sgr0) ]\tEnter the gif's number: "
read index

array_pos=$(( $index - 1 ))
files_count=$(( ${#files[@]} - 1 ))

for i in $(seq 0 $files_count); do
    if [ $i -eq $array_pos ]; then
        if [ $(uname -s) = 'Linux' ]; then
            echo "${db_path}${files[ $i ]}" | xclip -sel clip
        elif [ $(uname -s) = 'Darwin' ]; then
            echo "${db_path}${files[ $i ]}" | pbcopy
        fi

        break;
    fi
done